import os
from django.core.management.base import BaseCommand
from catalog.models import Author, Book, Language, Genre
from django.conf import settings
import random
import string

def random_gradient():
    gradients = [
        ("#a8edea", "#fed6e3"),
        ("#fcb69f", "#ffecd2"),
        ("#cfd9df", "#e2ebf0"),
        ("#f7971e", "#ffd200"),
        ("#a1c4fd", "#c2e9fb"),
        ("#fbc2eb", "#a6c1ee"),
        ("#fdcbf1", "#e0c3fc"),
        ("#f5f7fa", "#c3cfe2"),
        ("#f9d423", "#ff4e50"),
        ("#43cea2", "#185a9d"),
        ("#30cfd0", "#330867"),
        ("#5ee7df", "#b490ca"),
        ("#d299c2", "#fef9d7"),
        ("#f6d365", "#fda085"),
        ("#fbc2eb", "#a6c1ee"),
    ]
    return random.choice(gradients)

def make_svg(title, author, gradient, filename):
    svg = f'''<svg width="240" height="330" viewBox="0 0 240 330" fill="none" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="bg" x1="0" y1="0" x2="240" y2="330" gradientUnits="userSpaceOnUse">
      <stop stop-color="{gradient[0]}"/>
      <stop offset="1" stop-color="{gradient[1]}"/>
    </linearGradient>
  </defs>
  <rect width="240" height="330" rx="24" fill="url(#bg)"/>
  <text x="50%" y="45%" text-anchor="middle" fill="#222" font-size="22" font-family="Arial" font-weight="bold">{title[:18]}</text>
  <text x="50%" y="60%" text-anchor="middle" fill="#555" font-size="16" font-family="Arial">{author[:18]}</text>
</svg>'''
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(svg)

class Command(BaseCommand):
    help = 'Seed the database with many demo authors and books, each with a unique SVG cover.'

    def handle(self, *args, **kwargs):
        # 1. 语言
        languages = ['English', 'Chinese', 'French', 'German', 'Japanese', 'Russian', 'Spanish', 'Italian', 'Arabic', 'Korean']
        language_objs = {}
        for lang in languages:
            obj, _ = Language.objects.get_or_create(name=lang)
            language_objs[lang] = obj

        # 2. 体裁
        genres = ['Novel', 'Essay', 'Science Fiction', 'Philosophy', 'History', 'Biography', 'Poetry', 'Fantasy', 'Mystery', 'Romance', 'Adventure']
        genre_objs = {}
        for g in genres:
            obj, _ = Genre.objects.get_or_create(name=g)
            genre_objs[g] = obj

        # 3. 作者
        author_names = [
            '史铁生', 'J.K. Rowling', 'George Orwell', 'Jane Austen', '鲁迅', '村上春树', 'Fyodor Dostoevsky',
            'Gabriel García Márquez', 'Virginia Woolf', 'Franz Kafka', 'Ernest Hemingway', 'Leo Tolstoy',
            'Mark Twain', 'Haruki Murakami', 'Agatha Christie', 'J.R.R. Tolkien', 'Cao Xueqin', 'Charles Dickens',
            'Emily Brontë', 'Homer', 'Victor Hugo', 'Miguel de Cervantes', 'Dante Alighieri', 'Jules Verne',
            'Arthur Conan Doyle', 'Stephen King', 'Isabel Allende', 'Mo Yan', 'Yu Hua', 'Eileen Chang', 'Marcel Proust',
            'Margaret Atwood', 'Umberto Eco', 'Kazuo Ishiguro', 'Orhan Pamuk', 'Chimamanda Ngozi Adichie',
            'Khaled Hosseini', 'Elena Ferrante', 'Patrick Modiano', 'Alice Munro', 'Toni Morrison',
            'Naguib Mahfouz', 'Mario Vargas Llosa'
        ]
        author_objs = {}
        for name in author_names:
            obj, _ = Author.objects.get_or_create(name=name)
            author_objs[name] = obj

        # 4. 书籍（部分经典+自动生成）
        books_data = [
            {'title': '我与地坛', 'author': '史铁生', 'summary': '一部关于生命、苦难与思考的散文集。', 'language': 'Chinese', 'genre': ['Essay']},
            {'title': '务虚笔记', 'author': '史铁生', 'summary': '哲思与人生的交织，虚实之间的笔记。', 'language': 'Chinese', 'genre': ['Novel']},
            {'title': "Harry Potter and the Philosopher's Stone", 'author': 'J.K. Rowling', 'summary': 'The first adventure of Harry Potter at Hogwarts.', 'language': 'English', 'genre': ['Novel', 'Fantasy']},
            {'title': '1984', 'author': 'George Orwell', 'summary': 'A dystopian novel about totalitarianism and surveillance.', 'language': 'English', 'genre': ['Science Fiction']},
            {'title': 'Pride and Prejudice', 'author': 'Jane Austen', 'summary': 'A classic novel of manners and marriage.', 'language': 'English', 'genre': ['Novel']},
            {'title': '呐喊', 'author': '鲁迅', 'summary': '中国现代文学的奠基之作，收录多篇经典短篇小说。', 'language': 'Chinese', 'genre': ['Novel', 'Essay']},
            {'title': '挪威的森林', 'author': '村上春树', 'summary': '青春、孤独与成长的故事。', 'language': 'Japanese', 'genre': ['Novel']},
            {'title': '罪与罚', 'author': 'Fyodor Dostoevsky', 'summary': '一部关于罪恶与救赎的哲学小说。', 'language': 'Russian', 'genre': ['Philosophy', 'Novel']},
            {'title': '百年孤独', 'author': 'Gabriel García Márquez', 'summary': '魔幻现实主义的巅峰之作。', 'language': 'Spanish', 'genre': ['Novel']},
            {'title': '到灯塔去', 'author': 'Virginia Woolf', 'summary': '意识流文学的代表作。', 'language': 'English', 'genre': ['Novel']},
            {'title': '变形记', 'author': 'Franz Kafka', 'summary': '一部荒诞与现实交织的中篇小说。', 'language': 'German', 'genre': ['Novel']},
            {'title': '老人与海', 'author': 'Ernest Hemingway', 'summary': '一部关于坚持与尊严的小说。', 'language': 'English', 'genre': ['Novel', 'Adventure']},
            {'title': '战争与和平', 'author': 'Leo Tolstoy', 'summary': '俄国文学的巅峰之作。', 'language': 'Russian', 'genre': ['Novel', 'History']},
            {'title': '哈克贝利·费恩历险记', 'author': 'Mark Twain', 'summary': '美国文学经典冒险小说。', 'language': 'English', 'genre': ['Novel', 'Adventure']},
            {'title': '追忆似水年华', 'author': 'Marcel Proust', 'summary': '意识流文学的代表作。', 'language': 'French', 'genre': ['Novel']},
            {'title': '红楼梦', 'author': 'Cao Xueqin', 'summary': '中国古典小说巅峰之作。', 'language': 'Chinese', 'genre': ['Novel']},
            {'title': '雾都孤儿', 'author': 'Charles Dickens', 'summary': '英国现实主义小说代表作。', 'language': 'English', 'genre': ['Novel']},
            {'title': '呼啸山庄', 'author': 'Emily Brontë', 'summary': '英国文学经典爱情小说。', 'language': 'English', 'genre': ['Novel', 'Romance']},
            {'title': '荷马史诗', 'author': 'Homer', 'summary': '古希腊史诗巨著。', 'language': 'Greek', 'genre': ['Poetry', 'History']},
            {'title': '巴黎圣母院', 'author': 'Victor Hugo', 'summary': '法国浪漫主义文学代表作。', 'language': 'French', 'genre': ['Novel']},
        ]
        # 先为每个作者生成一本专属书
        for author in author_objs.keys():
            books_data.append({
                'title': f'{author}作品集',
                'author': author,
                'summary': f'这是{author}的代表作品集。',
                'language': random.choice(list(language_objs.keys())),
                'genre': random.sample(list(genre_objs.keys()), k=random.randint(1, 2))
            })
        # 再自动生成更多书
        for i in range(60):
            title = f"虚构之书 {i+1}"
            author = random.choice(list(author_objs.keys()))
            summary = f"这是一部自动生成的虚构小说，编号{i+1}。"
            lang = random.choice(list(language_objs.keys()))
            genre = random.sample(list(genre_objs.keys()), k=random.randint(1, 2))
            books_data.append({
                'title': title,
                'author': author,
                'summary': summary,
                'language': lang,
                'genre': genre
            })

        # 自动生成ISBN
        def random_isbn():
            return str(random.randint(1000000000000, 9999999999999))

        # 生成封面目录
        static_dir = os.path.join('catalog', 'static', 'images')
        os.makedirs(static_dir, exist_ok=True)

        for b in books_data:
            author = author_objs[b['author']]
            language = language_objs.get(b['language'], list(language_objs.values())[0])
            # 生成专属SVG封面
            safe_title = ''.join(c for c in b['title'] if c.isalnum())
            safe_author = ''.join(c for c in b['author'] if c.isalnum())
            svg_filename = f"book_{safe_title}_{safe_author}.svg"
            svg_path = os.path.join(static_dir, svg_filename)
            gradient = random_gradient()
            make_svg(b['title'], b['author'], gradient, svg_path)
            cover_url = f"/static/images/{svg_filename}"
            book, created = Book.objects.get_or_create(
                title=b['title'],
                defaults={
                    'author': author,
                    'summary': b['summary'],
                    'isbn': random_isbn(),
                    'language': language,
                    'cover_url': cover_url,
                }
            )
            # 体裁
            for g in b['genre']:
                if g in genre_objs:
                    book.genre.add(genre_objs[g])

        self.stdout.write(self.style.SUCCESS('Many demo authors and books with unique covers created successfully!')) 